package cn.diancan.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
/**
 * 过滤所有 「*.jsp」的请求
 * 通过实现servlet中的Filter接口
 */
public class NoJspFilter implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain chain) throws IOException, ServletException {
        //Sample---所有的*.jsp的请求，跳转到Action
       HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        String reqUrl= request.getRequestURL().toString();
        String basePath =getBasePath(request); 
        if(null!= basePath && null!= reqUrl && reqUrl.equals(basePath) ){
        	request.getRequestDispatcher("/index.html").forward(request, response); 
        }else{
        	response.sendRedirect("index.html"); 
        }
       
    }
    
    public String getBasePath(HttpServletRequest request){
		String path = request.getContextPath(); 
		String basePath = request.getScheme()+"://"+request.getServerName();
		if(80==request.getServerPort()){
			basePath=request.getScheme()+"://"+request.getServerName()+path+"/";
		}else{
			basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		} 
		return basePath;
	}

    public void destroy() {

    }

    public void init(FilterConfig arg0) throws ServletException {

    }
}